package com.matriq.cloudmanager.dialog;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;

import com.matriq.cloudmanager.R;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import net.lgpage.dialog.BaseDialog;
import net.lgpage.http.DownloadTask;
import net.lgpage.util.DownloadThread;

public class DownloadDialog extends BaseDialog {

	public DownloadDialog(Context context) {
		super(context);
		onCreate();
	}

	public TextView getTv_percent() {
		return tv_percent;
	}

	public void setTv_percent(TextView tv_percent) {
		this.tv_percent = tv_percent;
	}

	View view;

	public void onCreate() {
		view = LayoutInflater.from(getContext()).inflate(R.layout.dg_download,
				null);
		setViews();
		setEvents();
		loadData();
		setContentView(view);
	}

	TextView tv_prompt;
	Button bt_cancel;

	ProgressBar pb;
	TextView tv_percent;
	private void setViews() {
		tv_prompt = (TextView) view.findViewById(R.id.tv_prompt);
		tv_percent = (TextView) view.findViewById(R.id.tv_percent);
		bt_cancel = (Button) view.findViewById(R.id.bt_cancel);
		pb = (ProgressBar) view.findViewById(R.id.pb);
	}

	private void setEvents() {
		bt_cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if(task!=null){
					task.cancel();
					task = null;
				}
				cancel();
			}
		});
	}

	private void loadData() {

	}
	

	public Button getBt_cancel() {
		return bt_cancel;
	}

	public void setBt_cancel(Button bt_cancel) {
		this.bt_cancel = bt_cancel;
	}

	
	public ProgressBar getPb() {
		return pb;
	}

	public void setPb(ProgressBar pb) {
		this.pb = pb;
	}

	String prompt;

	String url;
	String filename;
	String realurl;
	public void setData(String prompt,String url,String filename) {
		this.prompt = prompt;
		this.url = url;
		if(this.url == null)this.url = "";
		this.filename = filename;
		tv_prompt.setText(prompt);
		StringBuilder sb = new StringBuilder();
		char cs[] = this.url.toCharArray();
		for(int i = 0;i<cs.length;i++){
			if(isChinese(cs[i])){
				try {
					sb.append(URLEncoder.encode(cs[i]+"","UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}else{
				sb.append(cs[i]);
			}
		}
		realurl = sb.toString();
	}
	
	  /* 下载包安装路径 */  
    private static final String dir = "/sdcard/dowish/download/";  
  
    /* 进度条与通知ui刷新的handler和msg常量 */  
  
    private static final int DOWN_UPDATE = 1;  
      
    private static final int DOWN_OVER = 2;  
      
    long progress;
    long maxProgress;
    File file;
    DownloadThread thread;
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }
    private Handler mHandler = new Handler(){  
        public void handleMessage(Message msg) {  
            switch (msg.what) {  
            case DOWN_UPDATE:  
                pb.setProgress((int) progress);  
                pb.setMax((int) maxProgress);
               tv_percent.setText(progress*100/maxProgress+"%");
                break;  
            case DOWN_OVER:  
            	dismiss();
            	if(listener!=null)
    				listener.onDialogExecute(file);
                break;  
            default:  
                break;  
            }  
        };  
    };  
   /* public void download(){
        final DownloadThread thread = new DownloadThread(realurl, dir, filename);
        thread.setOnDownloadingListener(new OnDownloadingListener() {
			
			@Override
			public void onFinish(File file) {
				DownloadDialog.this.file = file;
				mHandler.sendEmptyMessage(DOWN_OVER);
			}
			
			@Override
			public void onDownloading(long progress, long maxlength) {
				DownloadDialog.this.progress = progress;
				DownloadDialog.this.maxProgress = maxlength;
				mHandler.sendEmptyMessage(DOWN_UPDATE);
			}
			
			@Override
			public void onCancel() {
				dismiss();
			}
		});
        thread.start();
       setListener(new DialogListener() {
			
			@Override
			public void onDialogExecute(Object... obj) {
				thread.stopDownload();
			}
		});
       show();  
    }*/
    
    public void download(){
    	if(task!=null){
    		task.cancel();
    	}
    	task = new DownloadTask(getContext()) {
			
    		
			@Override
			public void onException(Exception e) {
				super.onException(e);
				if(e instanceof MalformedURLException){
					dismiss();
					cancel();
				}
			}

			@Override
			public void onPostExecuteX(File result) {
				DownloadDialog.this.file = result;
				mHandler.sendEmptyMessage(DOWN_OVER);
			}

			@Override
			public void onProgressChange(long progress, long maxlength) {
				DownloadDialog.this.progress = progress;
				DownloadDialog.this.maxProgress = maxlength;
				mHandler.sendEmptyMessage(DOWN_UPDATE);
				super.onProgressChange(progress, maxlength);
			}
			
		};
		task.execute(realurl,dir,filename);
    }
    DownloadTask task;
   
}